import 'package:dio/dio.dart';
import 'package:logger/logger.dart';

import '../../../data/dio/api/bt_dio_network.dart';
import '../../../data/dio/api/bt_net_data_source.dart';
import '../../../data/stats/bt_log_pages.dart';
import '../../../data/stats/bt_log_pv_manger.dart';
import '../../../data/store/bt_hive_logon_store.dart';
import '../../../data/store/bt_logon_data.dart';

class BtLoginRepository {
  final logger = Logger();
  final BtNetDataSource network = BtDioNetwork();

  void login(int oauthType, String token, Function(bool success, String msg) onResult) async {
    var map = <String, dynamic>{};
    map["oauthType"] = oauthType;
    map["token"] = token;

    network.login('false', map).then((loginResult) {
      if (loginResult.isSuccess) {
        BtHiveLogonStore().putData(BtLogonData(
          token: loginResult.data!.token,
          userId: loginResult.data!.userInfo.userId,
          userType: loginResult.data!.userInfo.userType,
          nickname: loginResult.data!.userInfo.nickname,
          avatarUrl: loginResult.data!.userInfo.avatarUrl,
          avatarThumbUrl: loginResult.data!.userInfo.avatarThumbUrl,
          loginPkgName: loginResult.data!.userInfo.loginPkgName ?? '',
          country: loginResult.data!.userInfo.country ?? '',
          birthday: loginResult.data!.userInfo.birthday,
          availableCoins: loginResult.data!.userInfo.availableCoins ?? 0,
        ));

        if (oauthType == 3) {
          BtLogPvManger.stat(page: BtLogPages.appleLogin);
        } else if (oauthType == 4) {
          BtLogPvManger.stat(page: BtLogPages.quickLogin);
        }
        BtLogPvManger.stat(page: BtLogPages.loginSuccess);
      }

      onResult(loginResult.isSuccess, loginResult.isSuccess ? 'Login Success' : loginResult.msg);
    }).catchError((error) {
      // non-200 error goes here.
      switch (error.runtimeType) {
        case DioException:
          // Here's the sample to get the failed response error code and message
          final res = (error as DioException).response;
          logger.e('Got error : ${res?.statusCode} -> ${res?.statusMessage}');
          break;
        default:
          logger.e('Error occurred: $error');
          break;
      }
    });
  }
}
